package com.sanji.sjmallmodule.phoneshell;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.sanji.sjmallapp.BaseActivity;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallutils.ImageUtil;
import com.sanji.sjmallutils.MyWebChomeClient;
import com.sanji.sjmallutils.Tools;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 加载 kkmoveUrl
 * Created by Administrator on 2017/9/14.
 */

public class ShellWebViewActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.common_back_img)ImageView backImg;
    @BindView(R.id.common_title_tv)TextView titleTv;
    @BindView(R.id.kkmove_view)WebView kkmoveView;

    private WebSettings webSettings;

    private String kkmoveUrl;
    private ShellGoodsBean goodsBean;

    private ValueCallback<Uri> mUploadMsg;
    private ValueCallback<Uri[]> mUploadMsg5Plus;

    //是否大于 4.0
    private boolean upLollipop = false;
    private ImageUtil imageUtil;
    //0-定制，1-购物车编辑
    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kkmove_view);
        ButterKnife.bind(this);

        type = getIntent().getIntExtra("webType",0);
        kkmoveUrl = getIntent().getStringExtra("kkmoveUrl");
        if (type == 0){
            goodsBean = (ShellGoodsBean) getIntent().getSerializableExtra("goodsBean");
        }
        imageUtil = new ImageUtil(this,mHandler);

        initView();
    }

    private void initView(){
        backImg.setOnClickListener(this);
        titleTv.setText("小千定制");
        webSettings = kkmoveView.getSettings();
        //能够的调用JavaScript代码
        webSettings.setJavaScriptEnabled(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true);// 缩放至屏幕的大小
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        kkmoveView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http://www.3j1688.com/diy/web/callback")){
                    String[] params = url.split("&");
                    String uuid = "";
                    int size = params.length;
                    if (size > 0){
                        for (int i=0;i<size;i++){
                            if (params[i].contains("uuid")){
                                String[] uuids = params[i].split("=");
                                uuid = uuids[1];
                                break;
                            }
                        }
                    }
                    if ("".equals(uuid)){
                        Tools.toastTools(mCtx,"数据失败，请重试");
                    }else if (type==0){
                        intent = new Intent(mCtx,FirmShellOrderActivity.class);
                        intent.putExtra("goodsBean",goodsBean);
                        intent.putExtra("kkmoveId",uuid);
                        startActivity(intent);
                        finishActivity();
                    }else if (type==1){
                        //购物车编辑
                        intent = getIntent();
                        intent.putExtra("kkmoveId",uuid);
                        setResult(RESULT_OK,intent);
                        finishActivity();

                    }
                }else{
                    view.loadUrl(url);
                }
                return true;
            }
        });

        kkmoveView.setWebChromeClient(new MyWebChomeClient(new MyWebChomeClient.OpenFileChooserCallBack() {
            @Override
            public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
                mUploadMsg = uploadMsg;
                upLollipop = false;
                imageUtil.showDialog(kkmoveView);
            }

            @Override
            public boolean openFileChooserCallBackAndroid5(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                mUploadMsg5Plus = filePathCallback;
                upLollipop = true;
                imageUtil.showDialog(kkmoveView);
                return true;
            }
        }));

        kkmoveView.loadUrl(kkmoveUrl);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                if (kkmoveView.canGoBack()){
                    kkmoveView.goBack();
                    return true;
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.common_back_img:
                finishActivity();
                break;
        }
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case ConfigConts.PHOTO_REQUEST_CANCEL:
                    if (mUploadMsg != null){
                        mUploadMsg.onReceiveValue(null);
                    }
                    if (mUploadMsg5Plus!=null){
                        mUploadMsg5Plus.onReceiveValue(null);
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode != RESULT_OK){
            if (mUploadMsg != null){
                mUploadMsg.onReceiveValue(null);
            }
            if (mUploadMsg5Plus!=null){
                mUploadMsg5Plus.onReceiveValue(null);
            }
            return;
        }

        imageUtil.dismissDialog();
        switch (requestCode){
            case ConfigConts.PHOTO_REQUEST_TAKEPHOTO:
                File camera = imageUtil.getCameraPath();
                if (camera!=null){
                    Uri uri = Uri.fromFile(camera);
                    if (upLollipop){
                        mUploadMsg5Plus.onReceiveValue(new Uri[]{uri});
                    }else{
                        mUploadMsg.onReceiveValue(uri);
                    }
                }else{
                    Tools.toastTools(mCtx,"拍照失败，请重试");
                }
                break;
            case ConfigConts.PHOTO_REQUEST_GALLERY:
                Uri uri = data.getData();
                if (upLollipop){
                    mUploadMsg5Plus.onReceiveValue(new Uri[]{uri});
                }else{
                    mUploadMsg.onReceiveValue(uri);
                }
                break;
        }


        super.onActivityResult(requestCode, resultCode, data);
    }

    //    public void showOptions() {
//        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
//        alertDialog.setOnCancelListener(new ReOnCancelListener());
//        alertDialog.setTitle(R.string.options);
//        alertDialog.setItems(R.array.options, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                if (which == 0) {
//                    mSourceIntent = ImageUtil.choosePicture();
//                    startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
//                } else {
//                    mSourceIntent = ImageUtil.takeBigPicture(MyActivity.this);
//                    startActivityForResult(mSourceIntent, REQUEST_CODE_IMAGE_CAPTURE);
//                }
//            }
//        });
//        alertDialog.show();
//    }

    private class ReOnCancelListener implements DialogInterface.OnCancelListener {


        @Override
        public void onCancel(DialogInterface dialogInterface) {
            if (mUploadMsg != null) {
                mUploadMsg.onReceiveValue(null);
                mUploadMsg = null;
            }
            if (mUploadMsg5Plus != null) {
                mUploadMsg5Plus.onReceiveValue(null);
                mUploadMsg5Plus = null;
            }
        }
    }
}
